﻿using System;
using System.Data;
using System.IO;
using System.Windows.Forms;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using System.Data.SqlClient;

namespace RESTAURANT
{
    public partial class frmServer : Form
    {
        private string computerName;
        private SqlConnection conn;
        private Configurations config;
        private SqlCommand cmd;

        public frmServer()
        {
            InitializeComponent();
            config = new Configurations();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void rbtnSameServer_CheckedChanged(object sender, EventArgs e)
        {
            groupBox1.Enabled = false;
        }
        private void FindServer()
        {
            string servername;
            // Create a DataTable where we enumerate the available servers
            DataTable dtServers = SmoApplication.EnumAvailableSqlServers();
            //SmoApplication.EnumAvailableSqlServers(
            // If there are any servers at all
            if (dtServers.Rows.Count > 0)
            {
                // Loop through each server in the DataTable
                foreach (DataRow drServer in dtServers.Rows)
                {
                    servername = drServer["Name"].ToString();
                    if (!servername.Contains(@"\SQLEXPRESS"))
                        servername += @"\SQLEXPRESS";
                    if (servername != computerName)
                    {
                        cbServer.Items.Add(servername);
                    }
                }
                if (cbServer.Items.Count >= 1)
                    cbServer.SelectedIndex = 0;
                else
                {
                    MessageBox.Show("Không có server nào khác", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    rbtnSameServer.Checked = true;
                }
            }
        }
        private void rbtnDifferenceServer_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtnDifferenceServer.Checked)
            {
                groupBox1.Enabled = true;
                this.Cursor = Cursors.AppStarting;
                FindServer();
                this.Cursor = Cursors.Default;
            }
        }

        private void frmServer_Load(object sender, EventArgs e)
        {
            rbtnSameServer.Checked = true;
            computerName = System.Environment.MachineName;
            computerName += @"\SQLEXPRESS";
            conn = new SqlConnection(@"Server=.\SQLEXPRESS;Database=RESTAURANT;Trusted_Connection=true;");
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.AppStarting;
                if (rbtnSameServer.Checked)
                {
                    IsDatabaseExist();

                    if (Configurations.CreateConnectionConfig(Application.StartupPath + "\\khoisangviet.dat", computerName))
                        this.Close();
                    else
                    {
                        MessageBox.Show("Không thể kết nối dữ liệu!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                    if (rbtnDifferenceServer.Checked)
                    {
                        if (Configurations.CreateConnectionConfig(Application.StartupPath + "\\khoisangviet.dat", cbServer.Text, "sa", txtPass.Text))
                            this.Close();//Application.Restart();
                        else
                        {
                            MessageBox.Show("Không thể kết nối dữ liệu!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
        private bool ExecuteSQLStmt(string sql)
        {
            cmd = new SqlCommand(sql, conn);
            try
            {
                cmd.ExecuteNonQuery();
                conn.Close();
                return true;
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message.ToString());
                conn.Close();
                return false;
            }
        }
        private bool doBackup()
        {
            // Create a connection
            if (conn.State == ConnectionState.Open)
                conn.Close();
            conn = new SqlConnection(config.MasterConnectionString);
            if (conn.State == ConnectionState.Open)
                conn.Close();
            conn.Open();
            string sql = @"CREATE DATABASE RESTAURANT ON PRIMARY
                           (Name= RESTAURANT, filename ='D:\RESTAURANT.mdf', size=3,
                           filegrowth=10%)log on
                           (name=RESTAURANT_log, filename='D:\RESTAURANT_log.ldf',size=3,
                           filegrowth=1)";
            // Create a connection
            if (ExecuteSQLStmt(sql))
                CreateTableBtn();
            else
                MessageBox.Show("Database đã tồn tại");
            return true;
        }
        private void CreateTableBtn()
        {
            // Open the connection
            conn = new SqlConnection(config.ConnectionString);
            if (conn.State == ConnectionState.Open)
                conn.Close();
            conn.Open();
            SqlCommand __cmd = conn.CreateCommand();
            //FileInfo file = new FileInfo("C:\\myscript.sql");
            StreamReader __streamReader = new StreamReader("KhoiSangViet.sql");
            string script = __streamReader.ReadToEnd();
            string[] cmds = script.Replace("GO", "~").Split(new Char[] { '~' });
            foreach (string cmd in cmds)
            {
                __cmd.CommandType = CommandType.Text;
                __cmd.CommandText = cmd;
                int i = __cmd.ExecuteNonQuery();
            }
            if (conn.State == ConnectionState.Open)
                conn.Close();
            conn.Close();
        }
        private void IsDatabaseExist()
        {
            try
            {
                conn.Open();
            }
            catch
            {
                doBackup();
            }
        }                                                                                    
    }
}
